package com.hula.onion.book.server.spider.platforms.tounawang;

import com.alibaba.fastjson.JSONObject;
import com.hula.onion.book.server.common.CommonResponse;
import com.hula.onion.book.server.common.SpiderCommon;
import com.hula.onion.book.server.config.ResponseStatusEnum;
import com.hula.onion.book.server.utils.HttpUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.cookie.Cookie;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * Created by work on 2018/1/19.
 */
@Component("tounaSpider")
public class TounaSpider extends SpiderCommon {
    private static final String LOGIN_AUTH_URL = "http://www.touna.cn/auth.do";
    private static final String GET_ACCOUT_INFO = "http://www.touna.cn/account.oneshop.do?method=loadAccountInfoNew";

    @Autowired
    private TounaSpiderHelper tounaSpiderHelper;

    @Override
    public CommonResponse execute() {
        //发送请求
        String loginAuthStr = HttpUtils.post(LOGIN_AUTH_URL, tounaSpiderHelper.installRequestParams(loginForm), getHttpContext());
        if (StringUtils.isEmpty(loginAuthStr)) {
            return new CommonResponse(ResponseStatusEnum.FAIL);
        }
        JSONObject authJson = JSONObject.parseObject(loginAuthStr);
        if ("200".equals(authJson.getString("status"))) {
            List<Cookie> cookies = getHttpContext().getCookieStore().getCookies();
            String accountUrl = GET_ACCOUT_INFO + "&subtime=" + String.valueOf(System.currentTimeMillis()) + "&csrftoken=";
            for (Cookie c : cookies) {
                if ("csrf-token".equals(c.getName())) {
                    accountUrl += c.getValue();
                    break;
                }
            }
            String accountStr = HttpUtils.get(accountUrl, getHttpContext());
            if (StringUtils.isEmpty(accountStr)) {
                return new CommonResponse(ResponseStatusEnum.QUERY_FAIL);
            }
            return tounaSpiderHelper.parseAccountBalance(accountStr);
        } else {
            return new CommonResponse(ResponseStatusEnum.ACCOUNT_ERROR);
        }
    }
}
